import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Divider, message, Select,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import router from 'umi/router';
import DescView from './descView';
import styles from '../UserManage.less';
import * as option from '../../../common/options';
import { powerBtnFunc } from '@/utils/utils';

const FormItem = Form.Item;

/* eslint react/no-multi-comp:0 */
@connect(({ Coupon, loading }) => ({
  Coupon,
  loading: loading.models.Coupon,
}))

@Form.create()
class Coupon extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    lookDescView: false,
    selectedRows: {},
    formValues: {},
    pagination: {
      pageNo: 1,
      pageSize: 15,
    },
  };

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'Coupon/fetch',
    });
  }


  status(val) {
    let str = '';
    if (val === 1) {
      str = '启用';
    } else {
      str = val === 2 ? '停用' : '删除';
    }
    return (<span>{str}</span>);
  }



  couponType(val) {
    return (<span>{option.couponType[val - 1].value}</span>);
  }

  columns = [
    {
      title: '编码',
      dataIndex: 'couponNo',
    },

    {
      title: '优惠券名称',
      dataIndex: 'couponName',
    },


    {
      title: '优惠券类型',
      dataIndex: 'couponType',
      render: val => (<span>{option.couponType[val - 1].value}</span>),

    },
    {
      title: '优惠券面值',
      dataIndex: 'couponValue',
    },
    {
      title: '发送数量',
      dataIndex: 'sendNum',
    },
    {
      title: '使用数量',
      dataIndex: 'useNum',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: val => (this.status(val)),
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          {powerBtnFunc('100090', [
            <a key={'edit'} onClick={() => this.handleUpdateModalVisible(true, record)}>修改</a>,
            <Divider key={'Divider'} type="vertical"/>],
          )}
          {powerBtnFunc('100089', [
            <a key={'view'} onClick={() => this.handleLookDesc(true, record)}>查看</a>,
          ])}


        </Fragment>
      ),
    },
  ];

  //  修改状态
  onChange(record) {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    dispatch({
      type: 'Coupon/status',
      payload: {
        bankNo: record.bankNo,
        status: record.status === 1 ? 2 : 1,
      },
      callback: (res) => {
        if (res.code === 200) {
          message.success('修改成功');
          dispatch({
            type: 'Coupon/fetch',
            payload: pagination,
          });
        } else {
          message.error(res.errMsg);
        }
      },
    });
  }


  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: 15,
      ...formValues,
    };

    dispatch({
      type: 'Coupon/fetch',
      payload: params,
    });
  };
  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'Coupon/fetch',
      payload: {},
    });
  };


  //搜索
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'Coupon/fetch',
        payload: values,
      });
    });
  };
  //新建
  handleModalVisible = flag => {
    router.push('/business/coupon/create');
  };
  //修改
  handleUpdateModalVisible = (flag, record) => {
    router.push({
      pathname: '/business/coupon/create',
      query: {
        couponNo: record.couponNo,
      },
    });
  };
  //查看
  handleLookDesc = (flag, record) => {
    this.setState({
      lookDescView: !!flag,
      selectedRows: record,
    }, () => {
      if (!!flag) {
        const { dispatch } = this.props;
        dispatch({
          type: 'Coupon/getDesc',
          payload: { CouponNo: record.couponNo },
        });
      }
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="优惠券名称">
              {getFieldDecorator('couponName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="优惠券类型">
              {getFieldDecorator('couponType')(
                <Select placeholder='请选择优惠券类型' style={{ width: '100%' }}>
                  <Select.Option value={''} key={''}>全部</Select.Option>
                  {option.couponType.map((item) => {
                    return (<Select.Option value={item.key} key={item.key}>{item.value}</Select.Option>);
                  })}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('status')(
                <Select placeholder='请选择状态' style={{ width: '100%' }}>
                  <Select.Option value={''} key={''}>全部</Select.Option>
                  <Select.Option value={1} key={'1'}>启用</Select.Option>
                  <Select.Option value={2} key={'2'}>停用</Select.Option>
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>

        </span>
          </Col>
        </Row>
      </Form>

    );
  }


  render() {
    const { Coupon: { data, Desc }, loading } = this.props;
    const { selectedRows, lookDescView } = this.state;
    return (
      <PageHeaderWrapper title="优惠券管理">
        <Card bordered={false}>

          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <div className={styles.tableListOperator}>
              {
                powerBtnFunc('100090',
                  <Button icon="plus" key={'create'} type="primary" onClick={() => this.handleModalVisible(true)}>
                    新建
                  </Button>,
                )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data ? data : []}
              rowKey='couponNo'
              rowSelectHide={true}
              columns={this.columns}
              onChange={this.handleStandardTableChange}
            />

          </div>
        </Card>
        <DescView
          handleLookDesc={this.handleLookDesc}
          selectedRows={Desc ? Desc : {}}
          lookDescView={lookDescView}/>
      </PageHeaderWrapper>
    );
  }
}

export default Coupon;
